﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Passwords.Models;
using System.Collections.ObjectModel;

namespace Passwords.Utils
{
    public static class ListUtil
    {
        const int maxAnimatableItems = 80;

        public static void Fill(ObservableCollection<PasswordContract> target, IList<PasswordContract> items)
        {
            if (items == null || items.Count == 0)
            {
                target.Clear();
            }
            else
            {
                if (items.Count < maxAnimatableItems && target.Count < maxAnimatableItems)
                {
                    Dictionary<PasswordContract, bool> hash = items.ToDictionary(c => c, v => true);

                    for (int i = 0; i < target.Count; i++)
                    {
                        PasswordContract p = target[i];
                        if (!hash.ContainsKey(p))
                        {
                            target.RemoveAt(i);
                            i--;
                        }
                    }

                    hash = target.ToDictionary(c => c, v => true);
                    for (int i = 0; i < items.Count; i++)
                    {
                        PasswordContract p = items[i];
                        if (!hash.ContainsKey(p))
                        {
                            target.SortInto(p);
                        }
                    }
                }
                else
                {
                    target.Clear();
                    foreach (PasswordContract p in items) target.Add(p);
                }
            }
        }
    }
}
